package ms.unicorn.util;

import ms.unicorn.dsl.IEditPartAware;
import ms.unicorn.dsl.IFigureEx;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPart;

public class FigureUtil {

	public static final IFigure NULL_FIGURE = new Figure();
	
	public static IFigure getChildFigure(IFigure figure, String childName) {
		if (figure instanceof IFigureEx)
			if (childName.equals(((IFigureEx) figure).getName())) return figure;
		for (Object child: figure.getChildren())
			if (child instanceof IFigure) {
				IFigure fig = getChildFigure((IFigure) child, childName);
				if (fig != null)
					return fig;
			}
		return null;
	}

	public static IFigure getChildFigure(IFigure figure, int flag) {
		if (figure instanceof IFigureEx)
			if ((((IFigureEx) figure).getFlag() & flag) > 0) return figure;
		for (Object child: figure.getChildren())
			if (child instanceof IFigure) {
				IFigure fig = getChildFigure((IFigure) child, flag);
				if (fig != null)
					return fig;
			}
		return null;
	}
	
	public static IFigureEx findParentFigureEx(IFigure figure) {
		while (figure != null && !(figure instanceof IFigureEx)) figure = figure.getParent();
		return (IFigureEx) figure;
	}
	
	public static EditPart resolveEditPart(IFigure figure) {
		while (figure != null && !(figure instanceof IEditPartAware)) figure = figure.getParent();
		return ((IEditPartAware) figure).getEditPart();
	}
}
